package com.afdor.rws.event.driven.channel.local.observer;

import com.afdor.rws.event.driven.api.EventHolder;
import com.afdor.rws.event.driven.entities.Event;
import com.afdor.rws.event.driven.support.holder.EventResult;
import lombok.Getter;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

import java.util.EventObject;
import java.util.concurrent.CompletableFuture;

/**
 * Created by zhaofujun on 2017/6/22.
 */
@Slf4j
public class ObserverEvent<V> extends EventObject implements EventHolder {

    @Getter
    @NonNull
    private final CompletableFuture<EventResult<V>> completableFuture;

    /**
     * Constructs a prototypical Event.
     *
     * @param event The object on which the Event initially occurred.
     * @throws IllegalArgumentException if source is null.
     */
    public ObserverEvent(@NonNull Event event, CompletableFuture<EventResult<V>> completableFuture) {
        super(event);
        this.completableFuture = completableFuture;
    }

    @Override
    public Event getEvent() {
        return (Event) getSource();
    }

    /**
     * 事件处理成功
     *
     * @param data
     */
    public void complete(V data) {
        complete(data, null);
    }

    /**
     * 事件处理成功
     *
     * @param data
     * @param message
     */
    public void complete(V data, String message) {
        if (completableFuture != null) {
            EventResult<V> result = new EventResult<>((Event) getSource());
            result.setCode(1);
            result.setData(data);
            result.setMessage(message);
            completableFuture.complete(result);
        }
    }

    /**
     * 事件处理失败
     *
     * @param message
     */
    public void failure(String message) {
        failure(message);
    }

    /**
     * 事件处理失败
     *
     * @param data
     * @param message
     */
    public void failure(V data, String message) {
        if (completableFuture != null) {
            EventResult<V> result = new EventResult<>((Event) getSource());
            result.setCode(0);
            result.setData(data);
            result.setMessage(message);
            completableFuture.complete(result);
        }
    }

    /**
     * 推荐使用 failure();
     *
     * @param e
     * @deprecated
     */
    public void completeExceptionally(Throwable e) {
        if (completableFuture == null) {
            log.error("事件执行失败：" + getSource() + "\n", e);
        } else {
            completableFuture.completeExceptionally(e);
        }
    }


}
